import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { Modal } from 'ant-design-vue'
import { VueAxios } from './axios'
import { ACCESS_TOKEN, ADMIN_INFO } from '@/store/mutation-types'
import Router from 'vue-router'
import router from '@/router'

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  console.log(error.response)
  if (error.response) {
    const data = error.response.data
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 400) {
      notification.warning({
        message: '错误提示1',
        description: data.msg
      })
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      notification.error({
        message: '错误提示',
        description: data.msg
      })
      // if (token) {
      //   store.dispatch('Logout').then(() => {
      //     setTimeout(() => {
      //       window.location.reload()
      //     }, 1500)
      //   })
      // }
    }
    if (error.response.status === 403) {
      this.$error({
        title: '权限不足',
        content: '您没有权限进行此操作'
      })
    }
  }
  return Promise.reject(error)
}

request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, error => {
  return Promise.reject(error)
})

request.interceptors.response.use(response => {
  const data = response.data
  if (data.code === 400) {
    notification.warn({
      message: '错误提示',
      description: data.msg
    })
    return Promise.reject(data)
  } else if (data.code === 401) {
    notification.error({
      message: '错误提示',
      description: data.msg
    })
    store.commit('SET_TOKEN', '')
    store.commit('SET_ACTIONS', [])
    store.commit('SET_INFO', [])
    storage.remove(ACCESS_TOKEN)
    setTimeout(() => {
      window.location.reload()
    }, 1500)
  } else if (data.code === 403) {
    Modal.error({
      title: '权限不足',
      content: '您没有权限进行此操作'
    })
    return Promise.reject(data)
  }
  return Promise.resolve(data)
}, error => {
  return Promise.reject(error.response)
})

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, request)
  }
}

export default request

export {
  installer as VueAxios,
  request as axios
}
